package cn.hyh.core.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zjs on 2017/1/15.
 */

public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String getRealIp(HttpServletRequest request){
        /*
		 * nginx 设置realip
		 * */
        String ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }

        ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }

        return request.getRemoteAddr();
    }

    public static String GET(String url){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        HttpGet httpGet = new HttpGet(url);
        //设置连接的超时时间和读取超时时间
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(10000)  //设置连接超时时间
                .setSocketTimeout(10000)      //连接上，读取请求的超时时间。
                .setConnectionRequestTimeout(1000)
                //设置从connect Manager获取Connection 超时时间
                .build();
        httpGet.setConfig(config);
        try {

            resp = httpClient.execute(httpGet);
            int respCode = resp.getStatusLine().getStatusCode();
            if (respCode != 200) {
                logger.warn("http GET("+respCode+"):"+url);
                httpGet.abort();
                return "";
            }
            HttpEntity entity = resp.getEntity();
            if(null != entity){
                 return EntityUtils.toString(entity);
            }

        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.toString());
        }
        finally {


            if(resp != null){
                try {
                    resp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient != null){
                try {
                    httpClient.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
        return "";
    }

    public static String GET_OLD(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String POST(String url, Map<String, String> headers, JSONObject params)  {
        //HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        String res = null;
        try {
            HttpPost request = new HttpPost(url);
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    request.setHeader(key, headers.get(key));
                }
            }

            StringEntity entity = new StringEntity(params.toJSONString(), "UTF-8");
            request.setEntity(entity);
            HttpResponse response = httpClient.execute(request);
            //int respCode = resp.getStatusLine().getStatusCode();
            //if (respCode != 200) {
            //    logger.warn("http POST("+respCode+"):"+url);
            //    request.abort();
            //    return "";
            //}
            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                res = EntityUtils.toString(respEntity, "UTF-8");
            }
            return res;
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.toString());
        }finally {
            if(resp != null){
                try {
                    resp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public static String POST_FORM(String url, Map<String, String> headers, Map<String, Object> params)  {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        try {
            String res = null;
            HttpPost request = new HttpPost(url);
            List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry
                        .getValue().toString());
                pairList.add(pair);
            }
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    request.setHeader(key, headers.get(key));
                }
            }
            request.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
            HttpResponse response = httpClient.execute(request);
            //int respCode = resp.getStatusLine().getStatusCode();
            //if (respCode != 200) {
            //    logger.warn("http POST_FORM("+respCode+"):"+url);
            //    request.abort();
            //    return "";
            //}
            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                res = EntityUtils.toString(respEntity, "UTF-8");
            }
            return res;
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.toString());
        }finally {
            if(resp != null){
                try {
                    resp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }



    public static String POST(String url, Map<String, String> headers, JSONArray params)  {
        //HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse resp = null;
        String res = null;
        try {
            HttpPost request = new HttpPost(url);
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    request.setHeader(key, headers.get(key));
                }
            }

            StringEntity entity = new StringEntity(params.toJSONString(), "UTF-8");
            request.setEntity(entity);
            HttpResponse response = httpClient.execute(request);
            //int respCode = resp.getStatusLine().getStatusCode();
            //if (respCode != 200) {
            //    logger.warn("http POST("+respCode+"):"+url);
            //    request.abort();
            //    return "";
            //}
            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                res = EntityUtils.toString(respEntity, "UTF-8");
            }
            return res;
        }catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.toString());
        }finally {
            if(resp != null){
                try {
                    resp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }


    /**
     * 判断是否是Ajax请求。
     * @param request
     * @return
     */
    public static boolean isAjax(ServletRequest request){

        return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
    }





}
